Scroll Progress Bar

Functions

In C, a function is a block of code that performs a specific task and can be called from other parts of the program. Functions help in breaking down complex tasks into smaller, manageable parts, making code more organized and easier to maintain. Functions in C can have a return type (indicating the type of value they return) and can accept zero or more input parameters.

Usage and Syntax:

To declare and define a function in C, specify its return type, name, and the list of parameters (if any). The function's implementation is enclosed in curly braces {}.


return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {
    // Function implementation
    // ...
    return return_value; // (Only if the function has a return type)
}
Sample Code with Explanation and Output:

#include <stdio.h>

// Function to calculate the sum of two integers
int add(int a, int b) {
    return a + b;
}

// Function to find the maximum of two integers
int findMax(int x, int y) {
    return (x > y) ? x : y;
}

// Function to print a message n times
void printMessage(int n) {
    for (int i = 0; i < n; i++) {
        printf("Hello, world! %d\n", i + 1);
    }
}

int main() {
    int num1 = 10, num2 = 20;

    // Call the add function and store the result in 'sum'
    int sum = add(num1, num2);
    printf("Sum: %d\n", sum);

    // Call the findMax function and print the result
    int max = findMax(num1, num2);’
    printf("Max: %d\n", max);

    // Call the printMessage function
    printMessage(3);

    return 0;
}
Output:

Sum: 30
Max: 20
Hello, world! 1
Hello, world! 2
Hello, world! 3

Explanation:
  • In the sample code, define three functions: add, findMax, and printMessage.
  • The add function takes two integer parameters a and b and returns their sum.
  • The findMax function takes two integer parameters x and y and returns the maximum of the two.
  • The printMessage function takes an integer parameter n and prints the message "Hello, world!" n times using a loop.
  • In the main function, call these functions to perform specific tasks.
  • Call the add function to calculate the sum of num1 and num2 and print the result.
  • Call the findMax function to find the maximum of num1 and num2 and print the result.
  • Call the printMessage function to print the message "Hello, world!" three times.
  • Functions help in organizing code and allow for code reusability by allowing us to call the same block of code from different parts of the program.

What is a function in C?


Subroutine

What is the keyword used to define a function in C?


Function

What is the return type of a function that doesn't return any value in C?


Void

What is used to call a function in C?


Invoke

What is a function that calls itself in C?


Recursive